package com.iplant.base.utils.tasker;

import com.iplant.base.utils.general.CalendarTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;

public class TaskTimerBase {

    private static final Logger logger = LoggerFactory.getLogger(TaskTimerBase.class);
    public Runnable target;
    /**
     * 每日触发开始时刻
     */
    public Calendar minCalendar = CalendarTool.getDate();

    /**
     * 每日触发结束时刻
     */
    public Calendar maxCalendar = CalendarTool.getDate();

    /**
     * 总的触发次数
     */
    public int times = -1;

    public volatile boolean active = false;

    public volatile boolean alive = false;

    /**
     * 触发间隔休眠时间 ms
     */
    public int sleepTime = 10000;

    public void Run() {
        try {
            if (active)
                return;
            active = true;
            alive = true;


            new Thread(() -> {
                Calendar wNow;
                while (alive) {
                    if (times == 0) {
                        alive = false;
                        break;
                    }

                    try {
                        Thread.sleep(sleepTime);
                        wNow = Calendar.getInstance();
                        minCalendar.set(wNow.get(Calendar.YEAR), wNow.get(Calendar.MONTH), wNow.get(Calendar.DAY_OF_MONTH));
                        maxCalendar.set(wNow.get(Calendar.YEAR), wNow.get(Calendar.MONTH), wNow.get(Calendar.DAY_OF_MONTH));

                        if (wNow.compareTo(minCalendar) >= 0 && wNow.compareTo(maxCalendar) < 0) {
                            target.run();
                            if (times > 0)
                                times--;
                        }

                    } catch (Exception ex) {
                        logger.error("Run while", ex);
                    }
                }
            }).start();
        } catch (Exception ex) {
            logger.error("Run", ex);
        }
    }


    public void destroy() {
        alive = false;
    }
}
